//
//  BXPhotoVC.m
//  BXlive
//
//  Created by bxlive on 2019/5/27.
//  Copyright © 2019 cat. All rights reserved.
//

#import "BXPhotoVC.h"
#import "BXPhotoCell.h"
#import "BXPhotoModel.h"
#import <HXPhotoPicker.h>
#import "SDPhotoBrowser.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import <FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h>
#import <SLDeveloperTools/SLDeveloperTools.h>
#import <Masonry/Masonry.h>

@interface BXPhotoVC()<UICollectionViewDataSource, UICollectionViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,HXCustomNavigationControllerDelegate,HXCustomCameraViewControllerDelegate,SDPhotoBrowserDelegate>
@property(nonatomic,strong)UIView *navigationView;
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)NSMutableArray *imageArr;
@property (assign, nonatomic) NSInteger offset;
@property (strong, nonatomic) HXPhotoManager *manager;
//@property (strong, nonatomic) HXDatePhotoToolManager *toolManager;
@end

@implementation BXPhotoVC
-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}
-(NSMutableArray *)imageArr{
    if (!_imageArr) {
        _imageArr = [NSMutableArray array];
    }
    return _imageArr;
}
//
//- (HXDatePhotoToolManager *)toolManager {
//    if (!_toolManager) {
//        _toolManager = [[HXDatePhotoToolManager alloc] init];
//    }
//    return _toolManager;
//}

- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto];
        _manager.configuration.openCamera = YES;
        _manager.configuration.saveSystemAblum = NO;
        _manager.configuration.lookGifPhoto = NO;
        _manager.configuration.photoMaxNum = 9;
        _manager.configuration.rowCount = 4;
        _manager.configuration.themeColor = sl_normalColors;
//        _manager.configuration.restoreNavigationBar = YES;
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    [self setupNavigationView];
    [self.view setBackgroundColor:[UIColor sl_colorWithHex:0xFFFFFF]];
//    self.navigationItem.title = NSLocalizedString(@"照片墙", nil);
    [self setupView];
//    UIButton *uploadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    uploadBtn.frame = CGRectMake(0, 0, 40, 40);
//    uploadBtn.titleLabel.font =  SLPFFont(14);
//    [uploadBtn setTitleColor:sl_normalColors forState:UIControlStateNormal];
//    [uploadBtn setTitle:NSLocalizedString(@"上传", nil) forState:UIControlStateNormal];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:uploadBtn];
//    [uploadBtn addTarget:self action:@selector(uploadBtnClick) forControlEvents:UIControlEventTouchUpInside];
}

-(void)setupNavigationView{
    _navigationView = [UIView new];
    [self.view addSubview:_navigationView];
    [_navigationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(__kTopAddHeight+64);
    }];
    [_navigationView setBackgroundColor:[UIColor sl_colorWithHex:0xFFFFFF]];
    WS(weakSelf);
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn addTarget:self action:@selector(pop) forControlEvents:BtnTouchUpInside];
    [_navigationView addSubview:backBtn];
    [backBtn setImage:CImage(@"back_black") forState:BtnNormal];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.mas_equalTo(0);
        make.width.height.mas_equalTo(44);
    }];
    UILabel *label = [UILabel createLabelWithFrame:CGRectZero BackgroundColor:SLClearColor Text:NSLocalizedString(@"照片墙", nil) Font:SLBFont(__ScaleWidth(18)) TextColor:sl_textColors];
    label.textAlignment = 1;
    [_navigationView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(44);
        make.right.mas_equalTo(-44);
        make.centerY.equalTo(weakSelf.navigationView.mas_bottom).offset(-22);
        make.height.mas_equalTo(25);
    }];
    
    UIButton *uploadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_navigationView addSubview:uploadBtn];
    [uploadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.mas_equalTo(0);
        make.height.width.mas_equalTo(44);
    }];
    [uploadBtn setTitle:NSLocalizedString(@"上传", nil) forState:BtnNormal];
    [uploadBtn sl_setTitleColor:sl_normalColors];
    uploadBtn.titleLabel.font = SLPFFont(__ScaleWidth(14));
    [uploadBtn addTarget:self action:@selector(uploadBtnClick) forControlEvents:BtnTouchUpInside];
}

#pragma 上传
-(void)uploadBtnClick{
    [self alertController];
}

-(void)setupView{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(__ScaleWidth(15), __ScaleWidth(12), __ScaleWidth(12), __ScaleWidth(12));
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.autoresizingMask = (0x1<<6) - 1;
    self.collectionView.emptyDataSetSource = self;
    self.collectionView.emptyDataSetDelegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.alwaysBounceVertical = YES;
    self.collectionView.showsVerticalScrollIndicator = YES;
    [self.view addSubview:self.collectionView];

    
//   self.collectionView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0));
    WS(weakSelf);
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(weakSelf.navigationView.mas_bottom);
    }];
    
    [self.collectionView registerClass:[BXPhotoCell class] forCellWithReuseIdentifier:@"BXPhotoCell"];
    
    [self TableDragWithDown];
    

}

- (void)TableDragWithDown
{
    _offset = 0;
    [self createData];
}
#pragma mark - 加载更多
- (void)loadMoreData
{
    _offset = self.dataArr.count;
    [self createData];
}

-(void)createData{
    [[NewHttpRequestPort sharedNewHttpRequestPort] UserAlbumGetList:@{@"offset":[NSString stringWithFormat:@"%ld",(long)self.offset]} Success:^(id responseObject) {
        [self.collectionView headerEndRefreshing];
        [BGProgressHUD hidden];
        if([responseObject[@"code"] integerValue] == 0)
        {
            if (!self.offset) {
                [self.dataArr removeAllObjects];
                self.collectionView.hh_footerView.ignoredScrollViewContentInsetBottom = 0;
                self.collectionView.isNoMoreData = NO;
            }
            NSArray *dataArray = responseObject[@"data"];
            if (dataArray.count) {
                for (NSDictionary *dict in dataArray) {
                    BXPhotoModel *model = [BXPhotoModel objectWithDictionary:dict];
                    [self.dataArr addObject:model];
                }
            }else{
                self.collectionView.isNoMoreData = YES;
            }
        } else{
            [BGProgressHUD showInfoWithMessage:[responseObject valueForKey:@"msg"]];
        }
        self.collectionView.isRefresh = NO;
        self.collectionView.isNoNetwork = NO;
        [self.collectionView reloadData];
    
    } Failure:^(NSError *error) {
        [BGProgressHUD hidden];
        [self.collectionView headerEndRefreshing];
        self.collectionView.isRefresh = NO;
        self.collectionView.isNoNetwork = !error.isNetWorkConnectionAvailable;
    }];
}

#pragma - mark UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BXPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BXPhotoCell" forIndexPath:indexPath];
    if (indexPath.item<self.dataArr.count) {
        if ([self.dataArr[indexPath.item] isKindOfClass:[UIImage class]]) {
            cell.imageView.image = self.dataArr[indexPath.item];
        }else{
            BXPhotoModel *model = self.dataArr[indexPath.item];
            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.thumb] placeholderImage:CImage(@"video-placeholder")];
        }
    }else{
        cell.imageView.image = CImage(@"icon_photo_add");
    }
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(__ScaleWidth(106), __ScaleWidth(106));
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return __ScaleWidth(15);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return __ScaleWidth(15);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if (indexPath.item<self.dataArr.count) {
        SDPhotoBrowser *photoBrowser = [SDPhotoBrowser new];
        photoBrowser.delegate = self;
        photoBrowser.browserStyle = SDPhotoBrowserStyleAll;
        photoBrowser.currentImageIndex = indexPath.item;
        photoBrowser.imageCount = self.dataArr.count;
        photoBrowser.sourceImagesContainerView = self.collectionView;
        [photoBrowser show];
    
    }else{
        [self alertController];
    }
}
-(void)alertController{
    [self.manager clearSelectedList];
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:NSLocalizedString(@"请选择上传方式", nil) preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *paizhao = [UIAlertAction actionWithTitle:NSLocalizedString(@"拍照", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [self.view hx_showImageHUDText:NSLocalizedString(@"此设备不支持相机!", nil)];
            return;
        }
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"无法使用相机", nil) message:NSLocalizedString(@"请在设置-隐私-相机中允许访问相机", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"设置", nil), nil];
            [alert show];

#pragma clang diagnostic pop
        
            
            
            return;
        }
        [self hx_presentCustomCameraViewControllerWithManager:self.manager delegate:self];
    }];
    UIAlertAction *xiangce = [UIAlertAction actionWithTitle:NSLocalizedString(@"相册", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        [self hx_presentSelectPhotoControllerWithManager:self.manager delegate:self];
#pragma clang diagnostic pop
        
        
    }];
    [alertVc addAction:cancle];
    [alertVc addAction:paizhao];
    [alertVc addAction:xiangce];
    [self presentViewController:alertVc animated:YES completion:nil];
}
//拍照
- (void)customCameraViewController:(HXCustomCameraViewController *)viewController didDone:(HXPhotoModel *)model{
    model.selectIndexStr = @"1";
    [@[model] hx_requestImageWithOriginal:YES completion:^(NSArray<UIImage *> * _Nullable imageArray, NSArray<HXPhotoModel *> * _Nullable errorArray) {
        [self.dataArr addObjectsFromArray:imageArray];
        [self.collectionView reloadData];
        [self updateImageList:imageArray];
    }];
//    [self.toolManager getSelectedImageList:@[model] success:^(NSArray<UIImage *> *imageList) {
//        [self.dataArr addObjectsFromArray:imageList];
//        [self.collectionView reloadData];
//        [self updateImageList:imageList];
//    } failed:^{
//
//    }];
}
//相册
- (void)albumListViewController:(HXAlbumListViewController *)albumListViewController didDoneAllList:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photoList videos:(NSArray<HXPhotoModel *> *)videoList original:(BOOL)original{
    
    [allList hx_requestImageWithOriginal:original completion:^(NSArray<UIImage *> * _Nullable imageArray, NSArray<HXPhotoModel *> * _Nullable errorArray) {
        [self.dataArr addObjectsFromArray:imageArray];
        [self.collectionView reloadData];
        [self updateImageList:imageArray];
    }];
    
//    [self.toolManager getSelectedImageList:allList success:^(NSArray<UIImage *> *imageList) {
//        [self.dataArr addObjectsFromArray:imageList];
//        [self.collectionView reloadData];
//        [self updateImageList:imageList];
//    } failed:^{
//        
//    }];
}



#pragma mark  SDPhotoBrowserDelegate
- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    // 不建议用此种方式获取小图，这里只是为了简单实现展示而已
    BXPhotoCell *cell = (BXPhotoCell *)[self collectionView:self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
    return cell.imageView.image;

}
// 返回高质量图片的url
- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
     if ([self.dataArr[index] isKindOfClass:[UIImage class]]) {
         return nil;
        
    }else{
        BXPhotoModel *model = self.dataArr[index];
        return [NSURL URLWithString:model.image];
    }
    
}
// 设置头像
-(void)photoBrowser:(SDPhotoBrowser *)browser setAvatar:(NSInteger)avatar{
    if ([self.dataArr[avatar] isKindOfClass:[UIImage class]]) {
        return;
    }else{
        BXPhotoModel *model = self.dataArr[avatar];
        [[NewHttpRequestHuang sharedNewHttpRequestHuang] UserSaveAvatarWithAvatar:model.image Success:^(id responseObject) {
            [BGProgressHUD showInfoWithMessage:responseObject[@"msg"]];
        } Failure:^(NSError *error) {
            [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"设置失败", nil)];
        }];
    }
}
// 删除头像
-(void)photoBrowser:(SDPhotoBrowser *)browser delteAvatar:(NSInteger)avatar{
    if ([self.dataArr[avatar] isKindOfClass:[UIImage class]]) {
        return;
    }else{
        BXPhotoModel *model = self.dataArr[avatar];
        [[NewHttpRequestPort sharedNewHttpRequestPort] UserAlbumDelete:@{@"id":model.photoId} Success:^(id responseObject) {
            if([responseObject[@"code"] integerValue] == 0)
            {
                [self.dataArr removeObject:model];
                [self.collectionView reloadData];
            }else{
                [BGProgressHUD showInfoWithMessage:responseObject[@"msg"]];
            }
        } Failure:^(NSError *error) {
            [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"设置失败", nil)];
        }];
    }
}

-(void)dealloc{
    NSLog(@"dealller");
    [self.manager clearSelectedList];
}

-(NSString *)getFileName{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // 设置时间格式
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@%d.jpg",str,((arc4random() % 501) + 500)];
    return fileName;
}

-(void)updateImageList:(NSArray *)imageList{
    [self.dataArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[UIImage class]]) {
            NSData *data;
            if (UIImagePNGRepresentation(obj) == nil){
                data = UIImageJPEGRepresentation(obj, 0.8);
            } else {
                data = UIImagePNGRepresentation(obj);
            }
            [SLUpLoadAndDownloadTools uploadFileWithType:@"album" fileName:[self getFileName] data:data success:^(NSDictionary *jsonDic, BOOL flag, NSMutableArray *models) {
                if (flag) {
                    NSString *url = jsonDic[@"filePath"];
                    [self.imageArr addObject:url];
                    BOOL isFresh = NO;
                    if (self.imageArr.count == imageList.count) {
                        isFresh = YES;
                    }
                    [self updateImageUrl:url idx:idx isFresh:isFresh];
                }
            } failure:^(NSError *error) {
                
            }];
            
        }else{
            
        }
    }];
    
}

-(void)updateImageUrl:(NSString *)url idx:(NSInteger)idx isFresh:(BOOL)isFresh{
    [[NewHttpRequestPort sharedNewHttpRequestPort] UserAlbumSave:@{@"image":url} Success:^(id responseObject) {
        if([responseObject[@"code"] integerValue] == 0)
        {
            
            NSArray *dataArray = responseObject[@"data"];
            if (dataArray.count) {
                for (NSDictionary *dict in dataArray) {
                    BXPhotoModel *model = [BXPhotoModel objectWithDictionary:dict];
                    [self.dataArr replaceObjectAtIndex:idx withObject:model];
                }
            }
            if (isFresh) {
                NSLog(@"刷新了");
                [self.collectionView reloadData];
            }
        }
    } Failure:^(NSError *error) {
        
    }];
}



@end
